# 此接口用于上传单个dicom到Orthanc服务器上
from werkzeug.utils import secure_filename
import requests
import os
from requests.auth import HTTPBasicAuth
import random
import time
from pyorthanc import find, Orthanc
orthanc = Orthanc('http://localhost:8042',
                  username='orthanc', password='orthanc')

from Flask_run import db
from database.models.message import Message
from database.models.mri import Mri
from database.models.patient import Patient


def SaveFile(file):
   if file :#当确认有上传文件
      source_path='../Dicom_repository'
      if not os.path.isdir(source_path):
        os.mkdir(source_path)
      filename =str(time.time()+random.gauss(5, 1)) + ".dcm"
      savepath=os.path.join(source_path, filename)
      file.save(savepath)#保存文件，也可以直接写成f.save(os.path.join(UPLOAD_FOLDER,fname))
      return savepath

        
def UploadFile(path):
    url='http://localhost:8042'
    username='orthanc'
    password='orthanc'
    with open(path, 'rb') as f:
        dicom = f.read()
        print('Uploading: %s (%dMB)' % (path, len(dicom) / (1024 * 1024)))

    # 连接orthanc服务
    auth = HTTPBasicAuth(username, password)
    r = requests.post('%s/instances' % url, auth = auth, data = dicom)

    try:
        r.raise_for_status()
    except Exception as e:
        print(e)
        print('  not a valid DICOM file, ignoring it')
        return

    info = r.json()
    # 上传完毕

    if isinstance(info, dict):
        r2 = requests.get('%s/instances/%s/tags?short' % (url, info['ID']),
                          auth = auth)
        r2.raise_for_status()
        tags = r2.json()
        
        Study_info={'PatientName': tags['0010,0010'],'sex':tags['0010,0040'],'borndate':tags['0010,0030'],'fid': tags['0008,0050'],'pid':tags['0010,0020'],'Study_id':tags['0020,000d'],'check_date':tags['0008,0020'],'hospital':tags['0008,0080'],'device':tags['0008,0070'],'modality':tags['0008,0060']} 
        # print(Study_info)
        pid = Study_info['pid']
        study_id = Study_info['Study_id']
        fid = Study_info['fid']
        borndate = Study_info['borndate']
        check_date = Study_info['check_date']
        name = Study_info['PatientName']
        sex = Study_info['sex']
        big=int(check_date[:4])
        small=int(borndate[:4])
        age=big-small
        hospital = Study_info['hospital']
        device=Study_info['device']
        modality=Study_info['modality']
        # print('****************************')
        # print(pid,fid,borndate,check_date,name,sex,hospital,device,modality)
        
        # 根据检查病人是否存在
        patient = Patient.query.filter(Patient.pid == pid).first() 
        #patient = db.session.query(Patient).filter(Patient.pid == pid).first()
        if patient is None:
            #不存在则添加
            try:
                newpatient = Patient(name,sex,age,pid,hospital,borndate)
                db.session.add(newpatient)
                db.session.commit()
            except:
                msg = Message(501,{},"数据库写入异常")
                # db.session.rollback()
                return msg.response()
            else:
                patient = Patient.query.filter(Patient.pid == pid).first()
        #添加mri记录
            # 检查mri时候存在，不过没必要数据库设置F号唯一即可，重复插入会报错
        iffid = Mri.query.filter(Mri.fid == fid).first()  
        print(f"iffid is {iffid}")
        if iffid is None:   
            newmri = Mri(fid,patient.id,study_id,check_date,device,modality,1, "", "", "")
            db.session.add(newmri)
            db.session.commit()
        else:
        # 更新slice 目前存在的问题是关闭了服务后，如果上传了相同的dicom文件，这个slice数还是会+1，但是一直开启服务的情况下就能正常运行
            item = Mri.query.filter(Mri.fid == fid).first()
            item.slice = item.slice + 1
            db.session.commit()
        print('finish upload')
            


